package com.example.librarysysee.controller;

import com.example.librarysysee.constants.Constants;
import com.example.librarysysee.model.*;
import com.example.librarysysee.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    BookService bookService;

    @RequestMapping(value = "/addBook",produces = "application/json")
    public Result addBook(BookInfo bookInfo){
        log.info("bookInfo:{}",bookInfo);
        if(!StringUtils.hasLength(bookInfo.getBookName())
        || !StringUtils.hasLength(bookInfo.getAuthor())
        || bookInfo.getCount()<=0
        || !StringUtils.hasLength(bookInfo.getPublish())){
            return Result.fail("输入错误");
        }
        try {
            bookService.addBook(bookInfo);
        }catch(Exception e){
            return Result.fail("内部错误");
        }
        return Result.success("");
    }

    @RequestMapping("/getListByPage")
    public Result<PageResult<BookInfo>> getListByPage(PageRequest pageRequest, HttpSession session){
        log.info("查询列表信息， pageRequest:{}",pageRequest);

        if(pageRequest.getCurrentPage()<1){
            return Result.fail("非法参数");
        }
        PageResult<BookInfo> pageResult = bookService.getListByPage(pageRequest);
        return Result.success(pageResult);
    }
    @RequestMapping("/queryBookById")
    public BookInfo queryBookById(Integer bookId){
        log.info("bookId:",bookId);
        return bookService.queryBookById(bookId);
    }

    @RequestMapping("/updateBook")
    public Result updateBook(BookInfo bookInfo){
        log.info("更新图书，bookInfo:{}",bookInfo);
        if(bookInfo.getId()<0){
            return Result.fail(false,"id 不合法");
        }
        try{
            Integer res = bookService.updateBook(bookInfo);
            if(res <= 0)
                return Result.fail(false, "更新失败");
            return Result.success(true);
        }catch (Exception e){
            log.error("e:{}",e);
            return Result.fail(false, e.getMessage());
        }
    }
    @RequestMapping("/batchDelete")
    public boolean batchDelete(@RequestParam List<Integer> ids){
        log.info("删除图书，id:{}", ids);
        try{
            Integer res = bookService.batchDelete(ids);
            if(res <= 0) return false;
            return true;
        }catch (Exception e){
            log.error("e:{}",e);
            return false;
        }
    }
}
